import axios from 'axios'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASE_URL,
  withCredentials: true,
  timeout: 20000
})

type DataType = {
  msg?: string
}

const showStaus = (code?:number|string, data?:DataType) => {
  let result: string | undefined = ''
  let flag = false
  switch (code) {
    case 0: //视频上传接口用
      result = 'success'
      flag = true
      break
    case 1:
      result = 'success'
      flag = true
      break
    case '1000':
      result = 'success'
      flag = true
      break
    case '1002':
      result = data?.msg
      flag = true
      break
    case '1001':
      result = '数据为空'
      flag = true
      break
    case '1006':
      result = '数据不存在'
      flag = true
      break
    case '1004':
      result = '请先登录！'
      flag = true
      break
    case '1009':
      result = '参数验证错误'
      flag = true
      break
    default:
      break
  }
  // 进行通知
  // $message方法是我按需引入的element-ui中的提示组件，你可以替换成自己的提示组件
  if (result) {
    console.log(result)
  }
  return flag
}

// 请求
service.interceptors.request.use(
  config=> {
    const tokens = localStorage.getItem('token')
    if (tokens) {
      config.headers.Authorization = 'Bearer ' + tokens
    }

    return config
  },

  error => {
    error.message = '服务器异常，请联系管理员'
    return Promise.reject(error)
  }
)

// 响应
service.interceptors.response.use(
  response => {
    // 接口响应的逻辑处理 包括判断接口code，状态等给出提示，相关的统一处理 及返回结果
    const res = response.data
    const status = res.code
    let msg:boolean = false
    if (status < 200 || status==200 || status==401 || (status >= 300 && status != 401 && status != 500)) {
      msg = showStaus(res.code)
      if (typeof res.data === 'string') {
        res.data = { msg }
      } else {
        res.msg = msg
      }
      return Promise.resolve(res)
    } else if (status == 1000) {
      return res
    } else if (status == 500) {
      res.data = { msg: msg }
      return res
    } else {
      console.log('测试请求拦截')
    }
  },
  error => {
    error.message = '请求超时或服务器异常，请检查网络或联系管理员!'
    return Promise.reject(error)
  }
)

export default service
